package dynamic.wrapper.resultmap;




import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import dynamic.metadata.EntityClass;
import dynamic.metadata.EntityProperty;
import dynamic.toolkit.support.DColumnCache;
import dynamic.wrapper.segments.DSelectCache;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.apache.ibatis.type.JdbcType;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import dynamic.metadata.DTableFieldInfo;
/**
 * result 标签
 *
 * @author yulichang
 * @since 1.3.0
 */
@Getter
@Setter(AccessLevel.PACKAGE)
public class DResult implements DIResult {

    private boolean isId;

    private String index;

    private DSelectCache selectNormal;

    private String property;

    private Class<?> javaType;

    private JdbcType jdbcType;

    public DResult() {
    }


    @SuppressWarnings({"UnusedReturnValue", "unused"})
    public static class Builder {

        private final DResult result;

        public Builder(boolean isId, String index) {
            this.result = new DResult();
            result.isId = isId;
            result.index = index;
        }

        public Builder(boolean isId, String index, DSelectCache selectCache) {
            this.result = new DResult();
            result.isId = isId;
            result.index = index;
            result.selectNormal = selectCache;
            result.property = selectCache.getColumProperty();
            result.javaType = selectCache.getColumnType();
            result.jdbcType = Optional.ofNullable(selectCache.getTableFieldInfo()).map(DTableFieldInfo::getJdbcType).orElse(null);
        }

        public Builder property(EntityProperty property) {
            result.property = DColumnCache.getName(property);
            return this;
        }

        public <E> Builder column(EntityProperty column) {
            EntityClass entityClass = column.getEntityClass();
            Map<String, DSelectCache> normalMap = DColumnCache.getMapField(entityClass);
            String name = DColumnCache.getName(column);
            DSelectCache normal = normalMap.get(name);
            result.selectNormal = normal;
            if (StringUtils.isBlank(result.property)) {
                result.property = normal.getColumProperty();
            }
            if (Objects.isNull(result.javaType)) {
                result.javaType = normal.getColumnType();
            }
            if (Objects.isNull(result.jdbcType)) {
                result.jdbcType = Objects.isNull(normal.getTableFieldInfo()) ? null : normal.getTableFieldInfo().getJdbcType();
            }
            return this;
        }

        public Builder javaType(Class<?> javaType) {
            result.javaType = javaType;
            return this;
        }

        public Builder jdbcType(JdbcType jdbcType) {
            result.jdbcType = jdbcType;
            return this;
        }

        public DResult build() {
            return result;
        }

    }
}

